import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import kotlinx.coroutines.delay

@Composable
fun Greeting() {
    var btnColor by remember { mutableStateOf("unknown") }
    //方式一：将btnColor作为参数传递到另一个可组合方法中,方式一：rememberUpdatedState配合LaunchedEffect使用时，btnColor为最新值；
    timer(btnColor = btnColor)
    //方式二：直接使用btnColor,也就是说不将btnColor作用参数传递时，不必使用ememberUpdatedState，btnColor的值也是最新的。
    LaunchedEffect(key1 = Unit, block = {
        delay(8000)
        Log.e(">>>", "btnColor: $btnColor")
    })
    //点击btn时，会重组。
    Column {
        OutlinedButton(onClick = {
            btnColor = "black"
        }) {
            Text(text = "black btn")
        }
    }
}

@Composable
fun timer(btnColor: String) {
    Log.e(">>>", "compose: $btnColor")
    //rememberUpdatedState的使用场景是在LaunchedEffect中保持可组函数的入参为最新值。
    var rememberBtnColor = rememberUpdatedState(newValue = btnColor)
    LaunchedEffect(key1 = Unit, block = {
        delay(5000)
        Log.e(">>>", "btnColor: $btnColor")
        Log.e(">>>", "btnColor: ${rememberBtnColor.value}")
    })
}

